<?php
	include_once "common.php";
?>
<?
/**
 * Session.php
 *
 * The Session class is meant to simplify the task of keeping
 * track of logged in users and also guests.
 */
include("database.php");
include("mailer.php");
include("form.php");
include("display.php");

class Session
{
	var $username;     //Username given on sign-up
	var $userid;       //Random value generated on current login
	var $userlevel;    //The level to which the user pertains
	var $time;         //Time user was last active (page loaded)
	var $logged_in;    //True if user is logged in, false otherwise
	var $userinfo = array();  //The array holding all user info
	var $url;          //The page url current being viewed
	var $referrer;     //Last recorded site page viewed

	/* Class constructor */
	function Session()
	{
		$this->time = time();
		$this->startSession();
	}

	/**
	* startSession - Performs all the actions necessary to
	* initialize this session object. Tries to determine if the
	* the user has logged in already, and sets the variables
	* accordingly. Also takes advantage of this page load to
	* update the active visitors tables.
	*/
	function startSession()
	{
		global $database;  //The database connection
		session_start();   //Tell PHP to start the session

		/* Determine if user is logged in */
		$this->logged_in = $this->checkLogin();

		/**
		* Set guest value to users not logged in, and update
		* active guests table accordingly.
		*/
		if(!$this->logged_in)
		{
			$this->username = $_SESSION['username'] = GUEST_NAME;
			$this->userlevel = GUEST_LEVEL;
			$database->addActiveGuest($_SERVER['REMOTE_ADDR'], $this->time);
		}
		/* Update users last active timestamp */
		else
		{
			$database->addActiveUser($this->username, $this->time);
		}

		/* Remove inactive visitors from database */
		$database->removeInactiveUsers();
		$database->removeInactiveGuests();

		/* Set referrer page */
		if(isset($_SESSION['url']))
		{
			$this->referrer = $_SESSION['url'];
		}
		else
		{
			$this->referrer = "/";
		}

		/* Set current url */
		$this->url = $_SESSION['url'] = $_SERVER['PHP_SELF'];
	}

	/**
	* checkLogin - Checks if the user has already previously
	* logged in, and a session with the user has already been
	* established. Also checks to see if user has been remembered.
	* If so, the database is queried to make sure of the user's
	* authenticity. Returns true if the user has logged in.
	*/
	function checkLogin()
	{
		global $database;  //The database connection
		/* Check if user has been remembered */
		if(isset($_COOKIE[COOKIE_USER]) && isset($_COOKIE[COOKIE_ID]))
		{
			$this->username = $_SESSION['username'] = $_COOKIE[COOKIE_USER];
			$this->userid   = $_SESSION['userid']   = $_COOKIE[COOKIE_ID];
		}

		/* Username and userid have been set and not guest */
		if(isset($_SESSION['username']) && isset($_SESSION['userid']) && $_SESSION['username'] != GUEST_NAME)
		{
			/* Confirm that username and userid are valid */
			if($database->confirmUserID($_SESSION['username'], $_SESSION['userid']) != 0)
			{
				/* Variables are incorrect, user not logged in */
				unset($_SESSION['username']);
				unset($_SESSION['userid']);
				return false;
			}

			/* User is logged in, set class variables */
			$this->userinfo  = $database->getUserInfo($_SESSION['username']);
			$this->username  = $this->userinfo['username'];
			$this->userid    = $this->userinfo['userid'];
			$this->userlevel = $this->userinfo['userlevel'];
			return true;
		}
		/* User not logged in */
		else
		{
			return false;
		}
	}

	/**
	* login - The user has submitted his username and password
	* through the login form, this function checks the authenticity
	* of that information in the database and creates the session.
	* Effectively logging in the user if all goes well.
	*/
	function login($subuser, $subpass, $subremember)
	{
		global $database, $form;  //The database and form object

		/* Username error checking */
		$field = "user";  //Use field name for username
		if(!$subuser || strlen($subuser = trim($subuser)) == 0)
		{
			$form->setError($field, "* Username not entered");
		}
		else
		{
			/* Check if username is not alphanumeric */
			if(!eregi("^([0-9a-z])*$", $subuser))
			{
				$form->setError($field, "* Username not alphanumeric");
			}
		}

		/* Password error checking */
		$field = "pass";  //Use field name for password
		if(!$subpass)
		{
			$form->setError($field, "* Password not entered");
		}

		/* Return if form errors exist */
		if($form->num_errors > 0)
		{
			return false;
		}

		/* Checks that username is in database and password is correct */
		$subuser = stripslashes($subuser);
		$result = $database->confirmUserPass($subuser, md5($subpass));

		/* Check error codes */
		if($result == 1)
		{
			$field = "user";
			$form->setError($field, "* Username not found");
		}
		else if($result == 2)
		{
			$field = "pass";
			$form->setError($field, "* Invalid password");
		}
		else if($result == 3)
		{
			$field = "user";
			$form->setError($field, "* Account not verified");
		}

		/* Return if form errors exist */
		if($form->num_errors > 0)
		{
			return false;
		}

		/* Username and password correct, register session variables */
		$this->userinfo  = $database->getUserInfo($subuser);
		$this->username  = $_SESSION['username'] = $this->userinfo['username'];
		$this->userid    = $_SESSION['userid']   = $this->generateRandID();
		$this->userlevel = $this->userinfo['userlevel'];

		/* Insert userid into database and update active users table */
		$database->updateUserField($this->username, "userid", $this->userid);
		$database->addActiveUser($this->username, $this->time);
		$database->removeActiveGuest($_SERVER['REMOTE_ADDR']);

		/**
		* This is the cool part: the user has requested that we remember that
		* he's logged in, so we set two cookies. One to hold his username,
		* and one to hold his random value userid. It expires by the time
		* specified in constants.php. Now, next time he comes to our site, we will
		* log him in automatically, but only if he didn't log out before he left.
		*/
		if($subremember)
		{
			setcookie(COOKIE_USER, $this->username, time()+COOKIE_EXPIRE, COOKIE_PATH);
			setcookie(COOKIE_ID,   $this->userid,   time()+COOKIE_EXPIRE, COOKIE_PATH);
		}

		/* Login completed successfully */
		return true;
	}

	/**
	* logout - Gets called when the user wants to be logged out of the
	* website. It deletes any cookies that were stored on the users
	* computer as a result of him wanting to be remembered, and also
	* unsets session variables and demotes his user level to guest.
	*/
	function logout()
	{
		global $database;  //The database connection
		/**
		* Delete cookies - the time must be in the past,
		* so just negate what you added when creating the
		* cookie.
		*/
		if(isset($_COOKIE[COOKIE_USER]) && isset($_COOKIE[COOKIE_ID]))
		{
			setcookie(COOKIE_USER, "", time()-COOKIE_EXPIRE, COOKIE_PATH);
			setcookie(COOKIE_ID,   "", time()-COOKIE_EXPIRE, COOKIE_PATH);
		}

		/* Unset PHP session variables */
		unset($_SESSION['username']);
		unset($_SESSION['userid']);

		/* Reflect fact that user has logged out */
		$this->logged_in = false;

		/**
		* Remove from active users table and add to
		* active guests tables.
		*/
		$database->removeActiveUser($this->username);
		$database->addActiveGuest($_SERVER['REMOTE_ADDR'], $this->time);

		/* Set user level to guest */
		$this->username  = GUEST_NAME;
		$this->userlevel = GUEST_LEVEL;
	}

	/**
	* register - Gets called when the user has just submitted the
	* registration form. Determines if there were any errors with
	* the entry fields, if so, it records the errors and returns
	* 1. If no errors were found, it registers the new user and
	* returns 0. Returns 2 if registration failed.
	*/
	function register($subuser, $subpass, $subemail, $subcountry, $subgender, $securityCode)
	{
		global $database, $form, $mailer;  //The database, form and mailer object

		/* Username error checking */

		$field = "user";  //Use field name for username
		if(!$subuser || strlen($subuser = trim($subuser)) == 0)
		{
			$form->setError($field, "* Username not entered");
		}
		else
		{
			/* Spruce up username, check length */
			$subuser = stripslashes($subuser);
			if(strlen($subuser) < 5)
			{
				$form->setError($field, "* Username below 5 characters");
			}
			else if(strlen($subuser) > 30)
			{
				$form->setError($field, "* Username above 30 characters");
			}
			/* Check if username is not alphanumeric */
			else if(!eregi("^([0-9a-z])+$", $subuser))
			{
				$form->setError($field, "* Username not alphanumeric");
			}
			/* Check if username is reserved */
			else if(strcasecmp($subuser, GUEST_NAME) == 0)
			{
				$form->setError($field, "* Username reserved word");
			}
			/* Check if username is already in use */
			else if($database->usernameTaken($subuser))
			{
				$form->setError($field, "* Username already in use");
			}
			/* Check if username is banned */
			else if($database->usernameBanned($subuser))
			{
				$form->setError($field, "* Username banned");
			}
		}

		/* Password error checking */
		$field = "pass";  //Use field name for password
		if(!$subpass)
		{
			$form->setError($field, "* Password not entered");
		}
		else
		{
			/* Spruce up password and check length*/
			$subpass = stripslashes($subpass);
			if(strlen($subpass) < 4)
			{
				$form->setError($field, "* Password too short");
			}
			/* Check if password is not alphanumeric */
			else if(!eregi("^([0-9a-z])+$", ($subpass = trim($subpass))))
			{
				$form->setError($field, "* Password not alphanumeric");
			}
		}

		/* Email error checking */
		$field = "email";  //Use field name for email
		if(!$subemail || strlen($subemail = trim($subemail)) == 0)
		{
			$form->setError($field, "* Email not entered");
		}
		else
		{
			/* Check if valid email address */
			$regex = "^[_+a-z0-9-]+(\.[_+a-z0-9-]+)*"
			."@[a-z0-9-]+(\.[a-z0-9-]{1,})*"
			."\.([a-z]{2,}){1}$";
			if(!eregi($regex,$subemail))
			{
				$form->setError($field, "* Email invalid");
			}
			else if($database->emailTaken(md5($subemail)))
			{
				$form->setError($field, "* Email already in use");
			}
			$subemail = stripslashes($subemail);
		}
		
		//captcha error checking
		$field = "security_code";
		if($_SESSION['security_code'] == $securityCode && !empty($_SESSION['security_code']))
		{
			unset($_SESSION['security_code']);
		}
		else
		{
			$form->setError($field, "* Captcha invalid");
		}

		/* Errors exist, have user correct them */
		if($form->num_errors > 0)
		{
			return 1;  //Errors with form
		}
		/* No errors, add the new account to the */
		else
		{
			$randID = $this->generateRandID();
			if($database->addNewUser($subuser, md5($subpass), $subemail, $subcountry, $subgender,$randID))
			{
				$this->addCountryCount($subcountry);
				if(EMAIL_WELCOME)
				{
					$mailer->sendWelcome($subuser,$subemail,$subpass,$randID);
				}
				return 0;  //New user added succesfully
			}
			else
			{
				return 2;  //Registration attempt failed
			}
		}
	}

	/**
	* editAccount - Attempts to edit the user's account information
	* including the password, which it first makes sure is correct
	* if entered, if so and the new password is in the right
	* format, the change is made. All other fields are changed
	* automatically.
	*/
	function changePass($subuser, $subcurpass, $subnewpass, $subconfirmnewpass)
	{
		global $database, $form;

		/* Password error checking */
		$field = "oldpass";  //Use field name for password
		if(!$subcurpass)
		{
			$form->setError($field, "* Password not entered");
		}

		/* Return if form errors exist */
		if($form->num_errors > 0)
		{
			return false;
		}

		/* Checks that username is in database and password is correct */
		$subuser = stripslashes($subuser);
		$result = $database->confirmUserPass($subuser, md5($subcurpass));
		
		if($result >= 1 && $result <= 3)
		{
			$field = "oldpass";
			$form->setError($field, "* Invalid password");
		}
		
		/* Return if form errors exist */
		if($form->num_errors > 0)
		{
			return false;
		}
		
		/* New Password error checking */
		$field = "newpass";
		if(!$subnewpass)
		{
			$form->setError($field, "* Password not entered");
		}
		else
		{
			/* Spruce up password and check length*/
			$subnewpass = stripslashes($subnewpass);
			if(strlen($subnewpass) < 4)
			{
				$form->setError($field, "* Password too short");
			}
			/* Check if password is not alphanumeric */
			else if(!eregi("^([0-9a-z])+$", ($subnewpass = trim($subnewpass))))
			{
				$form->setError($field, "* Password not alphanumeric");
			}
		}
		
		/* Confirm New Password error checking */
		$field = "confirmnewpass";
		if(!$subconfirmnewpass)
		{
			$form->setError($field, "* Confirm New Password not entered");
		}
		else
		{
			if(strcmp($subnewpass,$subconfirmnewpass)!=0)
			{
				$form->setError($field, "* Confirm New Password not the same");
			}
		}
		
		/* Return if form errors exist */
		if($form->num_errors > 0)
		{
			return false;
		}
		
		$this->editUserField("password", md5($subnewpass));
		return true;
	}

	/**
	* editUserField() - Edits certain user fields in a user's profile
	*/
	function editUserField($editField, $content)
	{
		global $database, $form;

		// Content Validation
		$field = "content";
		if(!$content || strlen($content = trim($content)) == 0)
		{
			$form->setError($field, "* Content not entered");
		}
		else
		{
			if(strlen($content) > 255)
			{
				$form->setError($field, "* Content may only contain a maximum of 255 characters");
			}
			$content = htmlspecialchars($content);
		}

		if($form->num_errors > 0)
		{
			return false;
		}
		else
		{
			return $database->query("UPDATE ".TBL_USERS." SET $editField = \"$content\" WHERE username = '".$this->username."'");
		}
	}

	/**
	* editUserInfo() - Edits user's optional info.
	*/
	function editUserInfo($subfname,$sublname,$subgender,$subcountry,$substate,$subcity,$subzip)
	{
		global $database, $form;

		/* First Name error checking */
		$field = "fname";
		if(strlen($subfname)>0)
		{
			$subfname = stripslashes($subfname);
			if(strlen($subfname) > 30)
			{
				$form->setError($field, "* First name above 30 characters");
			}
			/* Check if field is not alphanumeric */
			else if(!eregi("^([0-9a-z])+$", $subfname))
			{
				$form->setError($field, "* First name is not alphanumeric");
			}
		}

		/* Last Name error checking */
		$field = "lname";
		if(strlen($sublname)>0)
		{
			$sublname = stripslashes($sublname);
			if(strlen($sublname) > 30)
			{
				$form->setError($field, "* Last name above 30 characters");
			}
			/* Check if field is not alphanumeric */
			else if(!eregi("^([0-9a-z])+$", $sublname))
			{
				$form->setError($field, "* Last name is not alphanumeric");
			}
		}

		/* State error checking */
		$field = "state";
		if(strlen($substate)>0)
		{
			$substate = stripslashes($substate);
			if(strlen($substate) > 30)
			{
				$form->setError($field, "* State above 30 characters");
			}
			$substate = htmlspecialchars($substate);
		}

		/* City error checking */
		$field = "city";
		if(strlen($subcity)>0)
		{
			$subcity = stripslashes($subcity);
			if(strlen($subcity) > 30)
			{
				$form->setError($field, "* City above 30 characters");
			}
			$subcity = htmlspecialchars($subcity);
		}

		/* Zip code error checking */
		$field = "zip";
		if(strlen($subzip)>0)
		{
			$subzip = stripslashes($subzip);
			if(strlen($subzip) < 4)
			{
				$form->setError($field, "* Zip code below 4 characters");
			}
			else if(strlen($subzip) > 9)
			{
				$form->setError($field, "* Zip cod above 9 characters");
			}
			/* Check if username is not alphanumeric */
			else if(!eregi("^([[:space:]0-9a-z])+$", $subzip))
			{
				$form->setError($field, "* Zip code is not alphanumeric");
			}
		}

		if($form->num_errors > 0)
		{
			return false;
		}
		else
		{
			$this->minusCountryCount($this->username);

			$database->query("UPDATE ".TBL_USERS." SET fname='$subfname' WHERE username='".$this->username."'");
			$database->query("UPDATE ".TBL_USERS." SET lname='$sublname' WHERE username='".$this->username."'");
			$database->query("UPDATE ".TBL_USERS." SET gender='$subgender' WHERE username='".$this->username."'");
			$database->query("UPDATE ".TBL_USERS." SET country='$subcountry' WHERE username='".$this->username."'");
			$database->query("UPDATE ".TBL_USERS." SET state='$substate' WHERE username='".$this->username."'");
			$database->query("UPDATE ".TBL_USERS." SET city='$subcity' WHERE username='".$this->username."'");
			$database->query("UPDATE ".TBL_USERS." SET zip='$subzip' WHERE username='".$this->username."'");
			
			$result = $database->query("SELECT country FROM ".TBL_COUNTRIES." WHERE code='$subcountry'");
			$array = mysql_fetch_array($result);
			$database->query("UPDATE ".TBL_RESOURCES." SET country='".$array['country']."' WHERE username='".$this->username."'");
			
			$this->addCountryCount($subcountry);
			return true;
		}
	}

	/**
	* editContactInfo() - Edits user's contact info.
	*/
	function editContactInfo($subEmail,$subAIM,$subMSN,$subYahoo,$subICQ,$subSkype,$subJabber)
	{
		global $database, $form;

		/* Show email error checking */
		$field = "email";
		if(strlen($subEmail)>0)
		{
			$subEmail = stripslashes($subEmail);
			$regex = "^[_+a-z0-9-]+(\.[_+a-z0-9-]+)*"
			."@[a-z0-9-]+(\.[a-z0-9-]{1,})*"
			."\.([a-z]{2,}){1}$";
			if(!eregi($regex,$subEmail))
			{
				$form->setError($field, "* Email invalid");
			}
			else if(strlen($subEmail) > 50)
			{
				$form->setError($field, "* Email above 50 characters");
			}
		}

		/* AIM error checking */
		$field = "aim";
		if(strlen($subAIM)>0)
		{
			$subAIM = stripslashes($subAIM);
			if(strlen($subAIM) > 30)
			{
				$form->setError($field, "* AIM above 30 characters");
			}
			/* Check if field is not alphanumeric */
			else if(!eregi("^([0-9a-z])+$", $subAIM))
			{
				$form->setError($field, "* AIM is not alphanumeric");
			}
		}

		/* MSN error checking */
		$field = "msn";
		if(strlen($subMSN)>0)
		{
			$subMSN = stripslashes($subMSN);
			$regex = "^[_+a-z0-9-]+(\.[_+a-z0-9-]+)*"
			."@[a-z0-9-]+(\.[a-z0-9-]{1,})*"
			."\.([a-z]{2,}){1}$";
			if(!eregi($regex,$subMSN))
			{
				if(!eregi("^([0-9a-z])+$", $subMSN))
				{
					$form->setError($field, "* MSN invalid");
				}
			}
			else if(strlen($subMSN) > 50)
			{
				$form->setError($field, "* MSN above 50 characters");
			}
		}

		/* City error checking */
		$field = "yahoo";
		if(strlen($subYahoo)>0)
		{
			$subcity = stripslashes($subYahoo);
			$regex = "^[_+a-z0-9-]+(\.[_+a-z0-9-]+)*"
			."@[a-z0-9-]+(\.[a-z0-9-]{1,})*"
			."\.([a-z]{2,}){1}$";
			if(!eregi($regex,$subYahoo))
			{
				if(!eregi("^([0-9a-z])+$", $subYahoo))
				{
					$form->setError($field, "* Yahoo invalid");
				}
			}
			if(strlen($subYahoo) > 50)
			{
				$form->setError($field, "* Yahoo above 50 characters");
			}
		}


		/* ICQ error checking */
		$field = "icq";
		if(strlen($subICQ)>0)
		{
			$subICQ = stripslashes($subICQ);
			if(strlen($subICQ) > 30)
			{
				$form->setError($field, "* ICQ above 30 characters");
			}
			/* Check if field is not alphanumeric */
			else if(!eregi("^([0-9])+$", $subICQ))
			{
				$form->setError($field, "* ICQ is not numeric");
			}
		}

		/* Skype error checking */
		$field = "skype";
		if(strlen($subSkype)>0)
		{
			$subSkype = stripslashes($subSkype);
			if(strlen($subSkype) > 30)
			{
				$form->setError($field, "* Skype above 30 characters");
			}
			/* Check if field is not alphanumeric */
			else if(!eregi("^([0-9a-z])+$", $subSkype))
			{
				$form->setError($field, "* Skype is not alphanumeric");
			}
		}

		/* City error checking */
		$field = "jabber";
		if(strlen($subJabber)>0)
		{
			$subcity = stripslashes($subJabber);
			$regex = "^[_+a-z0-9-]+(\.[_+a-z0-9-]+)*"
			."@[a-z0-9-]+(\.[a-z0-9-]{1,})*"
			."\.([a-z]{2,}){1}$";
			if(!eregi($regex,$subJabber))
			{
				if(!eregi("^([0-9a-z])+$", $subJabber))
				{
					$form->setError($field, "* Jabber/Gtalk IM invalid");
				}
			}
			if(strlen($subJabber) > 50)
			{
				$form->setError($field, "* Jabber/Gtalk IM above 50 characters");
			}
		}

		if($form->num_errors > 0)
		{
			return false;
		}
		else
		{
			$database->query("UPDATE ".TBL_USERS." SET email='$subEmail' WHERE username='".$this->username."'");
			$database->query("UPDATE ".TBL_USERS." SET aim='$subAIM' WHERE username='".$this->username."'");
			$database->query("UPDATE ".TBL_USERS." SET msn='$subMSN' WHERE username='".$this->username."'");
			$database->query("UPDATE ".TBL_USERS." SET yahoo='$subYahoo' WHERE username='".$this->username."'");
			$database->query("UPDATE ".TBL_USERS." SET ICQ='$subICQ' WHERE username='".$this->username."'");
			$database->query("UPDATE ".TBL_USERS." SET skype='$subSkype' WHERE username='".$this->username."'");
			$database->query("UPDATE ".TBL_USERS." SET jabber='$subJabber' WHERE username='".$this->username."'");
			return true;
		}
	}

	/**
	* editPreferences() - Edits user's contact info.
	*/
	function editPreferences($messageNotify,$displayEmail)
	{
		global $database, $form;
		
		if($messageNotify)
			$messageNotify = 1;
		else
			$messageNotify = 0;
			
		if($displayEmail)
			$displayEmail = 1;
		else
			$displayEmail = 0;

		if($form->num_errors > 0)
		{
			return false;
		}
		else
		{
			$database->query("UPDATE ".TBL_USERS." SET messageNotify=$messageNotify, displayEmail=$displayEmail WHERE username='".$this->username."'");
			return true;
		}
	}

	function editLocation($latitude, $longitude)
	{
		global $database, $form;

		if($form->num_errors > 0)
		{
			return false;
		}
		else
		{
			$database->query("UPDATE ".TBL_USERS." SET longitude = $longitude, latitude = $latitude WHERE username='".$this->username."'");
			return true;
		}
	}

	/**
	* addComment() - Checks comment then sends to the database
	*/
	function addComment($attachid, $comment, $user)
	{
		global $database, $form;

		// Content Validation
		$field = "comment";
		if(!$comment || strlen($comment = trim($comment)) == 0)
		{
			$form->setError($field, "* Comment not entered");
		}
		else
		{
			if(strlen($comment) > 255)
			{
				$form->setError($field, "* Comment may only contain a maximum of 255 characters");
			}
			$comment = htmlspecialchars($comment);
		}
		$randID = $this->generateRandID();
		$time = time();

		if($form->num_errors > 0)
		{
			return false;
		}
		else
		{
			return $database->query("INSERT INTO ".TBL_COMMENTS." VALUES ('$randID', '$attachid', \"$comment\", '$user', '$time')");
		}
	}

	/**
	* sendMessage() - Validates fields then stores it into the database
	*/
	function sendMessage($to, $subject, $message)
	{
		global $database, $form, $mailer;

		// Subject Validation
		$field = "subject";
		if(!$subject || strlen($subject = trim($subject)) == 0)
		{
			$form->setError($field, "* Subject not entered");
		}
		else
		{
			$subject = stripslashes($subject);
			if(strlen($subject) < 5)
			{
				$form->setError($field, "* Subject must be above 5 characters");
			}
			else if(strlen($subject) > 62)
			{
				$form->setError($field, "* Subject must below 62 characters");
			}
			$subject = htmlspecialchars($subject);
		}

		// Message Validation
		$field = "message";
		if(!$message || strlen($message = trim($message)) == 0)
		{
			$form->setError($field, "* Message not entered");
		}
		else
		{
			if(strlen($message) > 65535)
			{
				$form->setError($field, "* Message may only contain a maximum of 65535 characters");
			}
			$message = htmlspecialchars($message);
		}
		$randID = $this->generateRandID();
		$time = time();

		if($form->num_errors > 0)
		{
			return false;
		}
		else
		{
			if($database->getUserInfo($to)!=NULL)
			{
				$result = $database->query("SELECT email,messageNotify FROM ".TBL_USERS." WHERE username='$to'");
				$dbarray = mysql_fetch_array($result);
				if($dbarray['messageNotify']=='1')
				{
					if($dbarray['email']!='')
					{
						$mailer->sendMessageNotify($dbarray['email'], $to, $this->username);
					}
				}
				return $database->query("INSERT INTO ".TBL_MESSAGES." VALUES ('$randID', '$to', '".$this->username."', '$subject', \"$message\", '$time', '0')");
			}
			return false;
		}
	}

	/**
	* addCategory() - Verifies fields then stores the category into the database.
	*/
	function addCategory($type, $category)
	{
		global $database, $form;

		// Title Validation
		$field = "category";
		if(!$category || strlen($category = trim($category)) == 0)
		{
			$form->setError($field, "* Name not entered");
		}
		else
		{
			$category = stripslashes($category);
			if(strlen($category) < 3)
			{
				$form->setError($field, "* Name must be above 3 characters");
			}
			else if(strlen($category) > 30)
			{
				$form->setError($field, "* Name must below 30 characters");
			}
			$category = htmlspecialchars($category);
		}

		$randID = $this->generateRandID();
		$time = time();

		if($form->num_errors > 0)
		{
			return false;
		}
		else
		{
			$database->query("INSERT INTO ".TBL_CATEGORIES." VALUES ('$type', '$category', '$randID', '$time', '".$this->username."')");
			return true;
		}
	}
	/**
	* addResource() - Verifies fields then stores the resource into the database.
	*/
	function addResource($type, $category, $title, $description, $latitude, $longitude)
	{
		global $database, $form, $session;

		// Type Validation
		$field = "type";
		if(!$type || strlen($type = trim($type)) == 0)
		{
			$form->setError($field, "* Type not chosen");
		}

		// Category Validation
		$field = "category";
		if(!$category || strlen($category = trim($category)) == 0)
		{
			$form->setError($field, "* Category not chosen");
		}

		// Title Validation
		$field = "title";
		if(!$title || strlen($title = trim($title)) == 0)
		{
			$form->setError($field, "* Name not entered");
		}
		else
		{
			$title = stripslashes($title);
			if(strlen($title) < 5)
			{
				$form->setError($field, "* Name must be above 5 characters");
			}
			else if(strlen($title) > 50)
			{
				$form->setError($field, "* Name must below 50 characters");
			}
			$title = htmlspecialchars($title);
		}

		// Description Validation
		$field = "description";
		if(!$description || strlen($description = trim($description)) == 0)
		{
			$form->setError($field, "* Description not entered");
		}
		else
		{
			if(strlen($description) < 5)
			{
				$form->setError($field, "* Please describe your resource");
			}
			else if(strlen($description) > 255)
			{
				$form->setError($field, "* Description may only contain a maximum of 255 characters");
			}
			$description = htmlspecialchars($description);
		}
		
		// Description Validation
		$field = "location";
		if(!$latitude || strlen($latitude = trim($latitude)) == 0)
		{
			$form->setError($field, "* Location not set");
		}

		if($form->num_errors > 0)
		{
			return false;
		}
		else
		{
			$time = time();
			$countryCode = $session->userinfo['country'];
			
			$result = $database->query("SELECT country FROM ".TBL_COUNTRIES." WHERE code='$countryCode'");
			$array = mysql_fetch_array($result);
			$database->query("INSERT INTO ".TBL_RESOURCES." (type, category, title, description, username, timestamp, countryCode, country, latitude, longitude) VALUES ('$type', '$category', '$title', \"$description\", '".$this->username."', '$time', '$countryCode', '".$array['country']."', '$latitude', '$longitude')");
			return true;
		}
	}
	/**
	* editResource() - Verifies fields then stores the edited resource into the database.
	*/
	function editResource($id, $type, $category, $title, $description, $latitude, $longitude)
	{
		global $database, $form;

		// Type Validation
		$field = "type";
		if(!$type || strlen($type = trim($type)) == 0)
		{
			$form->setError($field, "* Type not chosen");
		}

		// Category Validation
		$field = "category";
		if(!$category || strlen($category = trim($category)) == 0)
		{
			$form->setError($field, "* Category not chosen");
		}

		// Title Validation
		$field = "title";
		if(!$title || strlen($title = trim($title)) == 0)
		{
			$form->setError($field, "* Name not entered");
		}
		else
		{
			$title = stripslashes($title);
			if(strlen($title) < 5)
			{
				$form->setError($field, "* Name must be above 5 characters");
			}
			else if(strlen($title) > 50)
			{
				$form->setError($field, "* Name must below 50 characters");
			}
			$title = htmlspecialchars($title);
		}

		// Description Validation
		$field = "description";
		if(!$description || strlen($description = trim($description)) == 0)
		{
			$form->setError($field, "* Description not entered");
		}
		else
		{
			if(strlen($description) < 5)
			{
				$form->setError($field, "* Please describe your resource");
			}
			else if(strlen($description) > 255)
			{
				$form->setError($field, "* Description may only contain a maximum of 255 characters");
			}
			$description = htmlspecialchars($description);
		}

		if($form->num_errors > 0)
		{
			return false;
		}
		else
		{
			$database->query("UPDATE ".TBL_RESOURCES." SET type='$type', category='$category', title='$title', description=\"$description\", latitude='$latitude', longitude='$longitude' WHERE id='$id'");
			return true;
		}
	}
	
	/**
	* addLink() - Checks link vars for errors, thens sends to the database.
	*/
	function addLink($user, $link, $url, $description)
	{
		global $database, $form;
		
		//verify username
		if(strcmp($this->username,$user)!=0 && $this->userlevel<MANAGER_LEVEL)
		{
			return 2;
		}
		
		// Link Validation
		$field = "link";
		if($link || strlen($link = trim($link)) > 0)
		{
			if(strlen($link) > 50)
			{
				$form->setError($field, "* Link may contain 50 characters or less");
			}
			$link = htmlspecialchars($link);
		}
		
		// URL Validation
		$field = "url";
		if($url || strlen($url = trim($url)) > 0)
		{
			if(strlen($url) > 100)
			{
				$form->setError($field, "* URL may contain 100 characters or less");
			}
			$url = htmlspecialchars($url);
		}
		
		// Description Validation
		$field = "description";
		if(!$description || strlen($description = trim($description)) == 0)
		{
			$form->setError($field, "* Description not entered");
		}
		else
		{
			if(strlen($description) < 5)
			{
				$form->setError($field, "* Please describe your resource");
			}
			else if(strlen($description) > 255)
			{
				$form->setError($field, "* Description may only contain a maximum of 255 characters");
			}
			$description = htmlspecialchars($description);
		}
		
		
		if($form->num_errors > 0)
		{
			return 1;
		}
		else
		{
			$randID = $this->generateRandID();
			$time = time();
			if($database->query("INSERT INTO ".TBL_LINKS." (id,creator,link,url,description,timestamp) VALUES ('$randID', '$user', '$link', '$url', \"$description\", $time)"))
			{
				return 0;
			}
			else
			{
				return 2;
			}
		}
	}
	/**
	* editLink() - Checks link vars for errors, thens sends to the database.
	*/
	function editLink($id, $link, $url, $description, $creator)
	{
		global $database, $form;
		
		// Link Validation
		$field = "link";
		if($link || strlen($link = trim($link)) > 0)
		{
			if(strlen($link) > 50)
			{
				$form->setError($field, "* Link may contain 50 characters or less");
			}
			$link = htmlspecialchars($link);
		}
		
		// URL Validation
		$field = "url";
		if($url || strlen($url = trim($url)) > 0)
		{
			if(strlen($url) > 100)
			{
				$form->setError($field, "* URL may contain 100 characters or less");
			}
			$url = htmlspecialchars($url);
		}
		
		// Description Validation
		$field = "description";
		if(!$description || strlen($description = trim($description)) == 0)
		{
			$form->setError($field, "* Description not entered");
		}
		else
		{
			if(strlen($description) < 5)
			{
				$form->setError($field, "* Please describe your resource");
			}
			else if(strlen($description) > 255)
			{
				$form->setError($field, "* Description may only contain a maximum of 255 characters");
			}
			$description = htmlspecialchars($description);
		}
		
		// Creator or Admin Verification
		$field = "creator";
		if($this->userlevel < ADMIN_LEVEL)
		{
			$retval = $database->query("SELECT * FROM ".TBL_LINKS." WHERE id='$id' AND creator='$creator'");
			if(mysql_num_rows($retval)<=0)
			{
				$form->setError($field, "* You are not the creator of this link");
			}
		}
		
		if($form->num_errors > 0)
		{
			return 1;;
		}
		else
		{
			if($database->query("UPDATE ".TBL_LINKS." SET link='$link',url='$url',description=\"$description\" WHERE id='$id' AND creator='$creator'"))
			{
				return 0;
			}
			else
			{
				return 2;
			}
		}
	}

	/**
	* checkSearch() - Verifies text field for compatability
	*/
	function checkSearch($text)
	{
		global $database, $form;
		// Description Validation

		$field = "text";
		if($text || strlen($text = trim($text)) > 0)
		{
			if(strlen($text) > 100)
			{
				$form->setError($field, "* Text may only contain 100 characters");
			}
			$text = htmlspecialchars($text);
		}

		if($form->num_errors > 0)
		{
			return false;
		}
		else
		{
			return true;
		}
	}

	/**
	* addProject() - Verifies fields then stores the project into the database.
	*/
	function addProject($user, $name, $description, $isPrivate)
	{
		global $database, $form;

		// Title Validation
		$field = "name";
		if(!$name || strlen($name = trim($name)) == 0)
		{
			$form->setError($field, "* Name not entered");
		}
		else
		{
			$title = stripslashes($name);
			if(strlen($title) < 5)
			{
				$form->setError($field, "* Name must be above 5 characters");
			}
			else if(strlen($name) > 50)
			{
				$form->setError($field, "* Name must below 50 characters");
			}
			$name = htmlspecialchars($name);
		}

		// Description Validation
		$field = "description";
		if(!$description || strlen($description = trim($description)) == 0)
		{
			$form->setError($field, "* Description not entered");
		}
		else
		{
			if(strlen($description) < 5)
			{
				$form->setError($field, "* Please describe your resource");
			}
			else if(strlen($description) > 255)
			{
				$form->setError($field, "* Description may only contain a maximum of 255 characters");
			}
			$description = htmlspecialchars($description);
		}
		$randID = $this->generateRandID();
		$time = time();

		if($form->num_errors > 0)
		{
			return false;
		}
		else
		{
			$database->query("INSERT INTO ".TBL_PROJECTS." (id,name,description,creator,timestamp,isPrivate) VALUES ('$randID', '$name', \"$description\", '$user', $time, $isPrivate)");
			$database->query("INSERT INTO ".TBL_PROJECT_MEMBERS." (id,username,projectID,timestamp,userlevel) VALUES ('".$this->generateRandID()."', '$user', '$randID', $time, 9)");
			return true;
		}
	}
	
	/**
	* deleteProject() - Verifies owner or admin and deletes the project
	*/
	function deleteProject($projectID)
	{
		global $database;
		
		$result = $database->query("SELECT creator FROM ".TBL_PROJECTS." WHERE id='$projectID'");
		if(mysql_num_rows($result)<=0 && $this->userlevel<MANAGER_LEVEL)
		{
			return false;
		}
		
		$array = mysql_fetch_array($result);
		if(strcmp($array['creator'],$this->username)!=0 && $this->userlevel<MANAGER_LEVEL)
		{
			return false;
		}
		
		$database->deleteProject($projectID);
		return true;
	}

	/**
	* addNeededResource() - Verifies fields then stores the resource into the database.
	*/
	function addNeededResource($projectID, $type, $category, $title, $description)
	{
		global $database, $form;

		// Type Validation
		$field = "type";
		if(!$type || strlen($type = trim($type)) == 0)
		{
			$form->setError($field, "* Type not chosen");
		}

		// Category Validation
		$field = "category";
		if(!$category || strlen($category = trim($category)) == 0)
		{
			$form->setError($field, "* Category not chosen");
		}

		// Title Validation
		$field = "title";
		if(!$title || strlen($title = trim($title)) == 0)
		{
			$form->setError($field, "* Name not entered");
		}
		else
		{
			$title = stripslashes($title);
			if(strlen($title) < 5)
			{
				$form->setError($field, "* Name must be above 5 characters");
			}
			else if(strlen($title) > 50)
			{
				$form->setError($field, "* Name must below 50 characters");
			}
			/* Check if field is not alphanumeric */
			else if(!eregi("^([[:space:]0-9a-z])+$", $title))
			{
				$form->setError($field, "* Name is not alphanumeric");
			}
		}

		// Description Validation
		$field = "description";
		if(!$description || strlen($description = trim($description)) == 0)
		{
			$form->setError($field, "* Description not entered");
		}
		else
		{
			if(strlen($description) < 5)
			{
				$form->setError($field, "* Please describe your resource");
			}
			else if(strlen($description) > 255)
			{
				$form->setError($field, "* Description may only contain a maximum of 255 characters");
			}
			$description = htmlspecialchars($description);
		}
		$randID = $this->generateRandID();
		$time = time();

		if($form->num_errors > 0)
		{
			return false;
		}
		else
		{
			$database->query("INSERT INTO ".TBL_NEEDS." VALUES ('$randID', '$type', '$category', '$title', \"$description\", '$projectID', '$time')");
			return true;
		}
	}
	/**
	* editNeededResource() - Verifies fields then stores the edited resource into the database.
	*/
	function editNeededResource($id, $type, $category, $title, $description)
	{
		global $database, $form;

		// Type Validation
		$field = "type";
		if(!$type || strlen($type = trim($type)) == 0)
		{
			$form->setError($field, "* Type not chosen");
		}

		// Category Validation
		$field = "category";
		if(!$category || strlen($category = trim($category)) == 0)
		{
			$form->setError($field, "* Category not chosen");
		}

		// Title Validation
		$field = "title";
		if(!$title || strlen($title = trim($title)) == 0)
		{
			$form->setError($field, "* Name not entered");
		}
		else
		{
			$title = stripslashes($title);
			if(strlen($title) < 5)
			{
				$form->setError($field, "* Name must be above 5 characters");
			}
			else if(strlen($title) > 50)
			{
				$form->setError($field, "* Name must below 50 characters");
			}
			/* Check if field is not alphanumeric */
			else if(!eregi("^([[:space:]0-9a-z])+$", $title))
			{
				$form->setError($field, "* Name is not alphanumeric");
			}
		}

		// Description Validation
		$field = "description";
		if(!$description || strlen($description = trim($description)) == 0)
		{
			$form->setError($field, "* Description not entered");
		}
		else
		{
			if(strlen($description) < 5)
			{
				$form->setError($field, "* Please describe your resource");
			}
			else if(strlen($description) > 255)
			{
				$form->setError($field, "* Description may only contain a maximum of 255 characters");
			}
			$description = htmlspecialchars($description);
		}

		if($form->num_errors > 0)
		{
			return false;
		}
		else
		{
			$database->query("UPDATE ".TBL_NEEDS." SET type='$type', category='$category', title='$title', description=\"$description\" WHERE id='$id'");
			return true;
		}
	}
	/**
	* editProjectField() - Edits certain user fields in a project's profile
	*/
	function editProjectField($projectID, $editField, $content)
	{
		global $database, $form;

		// Content Validation
		$field = "content";
		if($editField=='details' || $editField=='application')
		{
			if($content || strlen($content = trim($content)) > 0)
			{
				$content = strip_tags($content,'<a>,<b>,<i>,<font>');
				if(strlen($content) > 65535)
				{
					$form->setError($field, "* Content cannot be longer than 65535 characters");
				}
				else if($this->broken_tags($content))
				{
					$form->setError($field, "* Content has broken HTML tags");
				}
				if($editField!='application')
					$content = nl2br($content);
			}
		}
		else
		{
			if(!$content || strlen($content = trim($content)) == 0)
			{
				$form->setError($field, "* Content not entered");
			}
			else
			{
				$content = strip_tags($content,'<a>,<b>,<i>,<font>');
				if(strlen($content) > 255)
				{
					$form->setError($field, "* Content may only contain a maximum of 255 characters");
				}
				else if($this->broken_tags($content))
				{
					$form->setError($field, "* Content has broken HTML tags");
				}
				$content = nl2br($content);
			}
		}

		if($form->num_errors > 0)
		{
			return false;
		}
		else
		{
			return $database->query("UPDATE ".TBL_PROJECTS." SET $editField = \"$content\" WHERE id = '$projectID'");
		}
	}
	/**
	* editProjectDetails() - Edits certain fields in a project's profile
	*/
	function editProjectDetails($projectID, $link, $moneyNeeded, $email)
	{
		global $database, $form;

		// Link Validation
		$field = "link";
		if($link || strlen($link = trim($link)) > 0)
		{
			if(strlen($link) > 255)
			{
				$form->setError($field, "* Link may only contain a maximum of 255 characters");
			}
			$link = htmlspecialchars($link);
		}

		// Money Needed Validation
		$field = "moneyNeeded";
		if($moneyNeeded || strlen($moneyNeeded = trim($moneyNeeded)) > 0)
		{
			if(strlen($moneyNeeded) > 10)
			{
				$form->setError($field, "* Link may only contain a maximum of 255 characters");
			}
			else if(ereg("[^[:space:]0-9.,$]{1,}", $moneyNeeded))
			{
				$form->setError($field, "* Link may contain only numeric characters and .,$");
			}
		}

		// Email Validation
		$field = "email";
		if(strlen($email)>0)
		{
			$email = stripslashes($email);
			$regex = "^[_+a-z0-9-]+(\.[_+a-z0-9-]+)*"
			."@[a-z0-9-]+(\.[a-z0-9-]{1,})*"
			."\.([a-z]{2,}){1}$";
			if(!eregi($regex,$email))
			{
				$form->setError($field, "* Email invalid");
			}
			else if(strlen($email) > 50)
			{
				$form->setError($field, "* Email above 50 characters");
			}
		}

		if($form->num_errors > 0)
		{
			return false;
		}
		else
		{
			return $database->query("UPDATE ".TBL_PROJECTS." SET link=\"$link\", moneyNeeded=\"$moneyNeeded\", email=\"$email\" WHERE id='$projectID'");
		}
	}

	/**
	* editProjectPreferences() - Edits certain preferences in a project's profile
	*/
	function editProjectPreferences($projectID,$applyNotify,$isPrivate,$allowApply)
	{
		global $database, $form;

		if($allowApply)
			$allowApply = 1;
		else
			$allowApply = 0;
		
		if($form->num_errors > 0)
		{
			return false;
		}
		else
		{
			return $database->query("UPDATE ".TBL_PROJECTS." SET applyNotify='$applyNotify', isPrivate='$isPrivate', allowApply='$allowApply' WHERE id='$projectID'");
		}
	}
	/**
	* editMemberLevel() - Checks if admin then edits the member userlevel
	*/
	function editMemberLevel($projectID, $user, $level)
	{
		global $database;
		
		//check if is a member
		$result = $database->query("SELECT userlevel FROM ".TBL_PROJECT_MEMBERS." WHERE projectID='$projectID' AND username='".$this->username."'");
		if(mysql_num_rows($result)<=0 && $this->userlevel<MANAGER_LEVEL)
		{
			return false;
		}
		
		//check if member is an admin
		$array = mysql_fetch_array($result);
		if($array['userlevel']<PROJECT_MANAGER && $this->userlevel<MANAGER_LEVEL)
		{
			return false;
		}
		
		//checks if change member is creator
		$result1 = $database->query("SELECT creator FROM ".TBL_PROJECTS." WHERE id='$projectID' AND creator='$user'");
		if(mysql_num_rows($result1)>0)
		{
			return false;
		}
		
		$database->query("UPDATE ".TBL_PROJECT_MEMBERS." SET userlevel=$level WHERE projectID='$projectID' AND username='$user'");
		return true;
	}
	/**
	* deleteProjectMember() - Checks if admin then deletes the member
	*/
	function deleteProjectMember($projectID, $user)
	{
		global $database;
		
		//check if is a member
		$result = $database->query("SELECT userlevel FROM ".TBL_PROJECT_MEMBERS." WHERE projectID='$projectID' AND username='".$this->username."'");
		if(mysql_num_rows($result)<=0 && $this->userlevel<MANAGER_LEVEL)
		{
			return false;
		}
		
		//check if member is an admin
		$array = mysql_fetch_array($result);
		if($array['userlevel']<PROJECT_MANAGER && $this->userlevel<MANAGER_LEVEL)
		{
			return false;
		}
		
		//check if delete member exists
		$result1 = $database->query("SELECT userlevel FROM ".TBL_PROJECT_MEMBERS." WHERE projectID='$projectID' AND username='$user'");
		if(mysql_num_rows($result1)<=0)
		{
			return false;
		}
		
		//check if delete member can be deleted
		$array1 = mysql_fetch_array($result1);
		if($array1['userlevel']==PROJECT_MANAGER)
		{
			return false;
		}
		
		$database->query("DELETE FROM ".TBL_PROJECT_MEMBERS." WHERE projectID='$projectID' AND username='$user'");
		return true;
	}
	/**
	* subApplication() - Validates fields then stores message into the database
	*/
	function subApplication($to, $from, $subject, $message, $email, $notifyType, $projectID)
	{
		global $database, $form, $mailer;
		
		//if logged in
		if(!$this->logged_in)
		{
			return false;
		}
		
		// Message Validation
		$field = "message";
		if(!$message || strlen($message = trim($message)) == 0)
		{
			$form->setError($field, "* Message not entered");
		}
		else
		{
			if(strlen($message) > 65535)
			{
				$form->setError($field, "* Message may only contain a maximum of 65535 characters");
			}
			$message = htmlspecialchars($message);
		}
		$randID = $this->generateRandID();
		$time = time();

		$result = $database->query("SELECT email,aim,msn,yahoo,icq,skype FROM ".TBL_USERS." WHERE username = '$from'");
		$dbarray = mysql_fetch_array($result);
		$body = $message;

		//add contact info
		if($dbarray['email']!='' || $dbarray['aim']!='' || $dbarray['msn']!='' || $dbarray['yahoo']!='' || $dbarray['icq']!='' || $dbarray['skype']!='')
		{
			$message .= "<br />";
			if($dbarray['email']!='')
			{
				$message .= "<br /><b>E-mail:</b> ".$dbarray['email'];
			}
			if($dbarray['aim']!='')
			{
				$message .= "<br /><b>AIM:</b> ".$dbarray['aim'];
			}
			if($dbarray['msn']!='')
			{
				$message .= "<br /><b>MSN:</b> ".$dbarray['msn'];
			}
			if($dbarray['yahoo']!='')
			{
				$message .= "<br /><b>Yahoo:</b> ".$dbarray['yahoo'];
			}
			if($dbarray['icq']!='0')
			{
				$message .= "<br /><b>ICQ:</b> ".$dbarray['icq'];
			}
			if($dbarray['skype']!='')
			{
				$message .= "<br /><b>Skype:</b> ".$dbarray['skype'];
			}
		}

		if($form->num_errors > 0)
		{
			return false;
		}
		else
		{
			//join project as applicant
			$retval = $database->query("SELECT isPrivate FROM ".TBL_PROJECTS." WHERE id='$projectID'");
			$projectArray = mysql_fetch_array($retval);
			if($projectArray['isPrivate']==1)
			{
				$retval2 = $database->query("SELECT * FROM ".TBL_PROJECT_MEMBERS." WHERE projectID='$projectID' AND username='$from'");
				if(mysql_num_rows($retval2)<=0)
				{
					$database->query("INSERT INTO ".TBL_PROJECT_MEMBERS." (id,username,projectID,timestamp,userlevel) VALUES ('".$this->generateRandID()."','$from','$projectID',$time,0)");
				}
			}
			
			//send email
			if($email!='' && $notifyType==0)
			{
				if($dbarray['email']!='' || $dbarray['aim']!='' || $dbarray['msn']!='' || $dbarray['yahoo']!='' || $dbarray['icq']!='' || $dbarray['skype']!='')
				{
					$body .= "\n\nContact Information";
					if($dbarray['email']!='')
					{
						$body .= "\nE-mail: ".$dbarray['email'];
					}
					if($dbarray['aim']!='')
					{
						$body .= "\nAIM: ".$dbarray['aim'];
					}
					if($dbarray['msn']!='')
					{
						$body .= "\nMSN: ".$dbarray['msn'];
					}
					if($dbarray['yahoo']!='')
					{
						$body .= "\nYahoo: ".$dbarray['yahoo'];
					}
					if($dbarray['icq']!=0)
					{
						$body .= "\nICQ: ".$dbarray['icq'];
					}
					if($dbarray['skype']!='')
					{
						$body .= "\nSkype: ".$dbarray['skype'];
					}
				}
				$mailer->sendApplication($email,$from,$subject,$body);
				return true;
			}
			else if($notifyType==1 || $email=='')
			{
				return $database->query("INSERT INTO ".TBL_MESSAGES." VALUES ('$randID', '$to', '$from', '$subject"." Application', \"$message\", '$time', '0')");
			}
		}
	}
	//leaveProject - Leave project by user
	function leaveProject($id, $user)
	{
		global $database, $form;
		
		return $database->query("DELETE FROM ".TBL_PROJECT_MEMBERS." WHERE username='$user' AND projectID='$id'");
	}
	//joinProject - Joins project by user
	function joinProject($id, $user)
	{
		global $database, $form;
		
		$result = $database->query("SELECT isPrivate FROM ".TBL_PROJECTS." WHERE id='$id'");
		if(mysql_num_rows($result)==1)
		{
			$arrayProject = mysql_fetch_array($result);
			
			if($arrayProject['isPrivate']==1)
			{
				return false;
			}
		}
		else
			return false;
		
		$database->query("INSERT INTO ".TBL_PROJECT_MEMBERS." (id,username,projectID,timestamp,userlevel) VALUES ('".$this->generateRandID()."','$user','$id',".time().",1)");
		return true;
	}
	
	/**
	* postProjectNews() - Posts given project by user.
	*/
	function postProjectNews($projectID, $title, $content)
	{
		global $database, $form;
		
		//Project ID error checking
		$field = "projectID";
		if($projectID=="")
		{
			$form->setError($field, "* ID is incorrect");
		}
		
		//Title error checking
		$field = "title";
		if(!$title || strlen($title = trim($title)) == 0)
		{
			$form->setError($field, "* Title not entered");
		}
		else
		{
			if(strlen($title) > 50)
			{
				$form->setError($field, "* Title cannot be longer than 50 characters");
			}
			$title = htmlspecialchars($title);
		}
		
		//Content error checking
		$field = "content";
		if(!$content || strlen($content = trim($content)) == 0)
		{
			$form->setError($field, "* Content not entered");
		}
		else
		{
			$content = strip_tags($content,'<a>,<b>,<i>,<font>');
			if(strlen($content) > 65535)
			{
				$form->setError($field, "* Content cannot be longer than 65535 characters");
			}
			else if($this->broken_tags($content))
			{
				$form->setError($field, "* Content has broken HTML tags");
			}
			$content = nl2br($content);
		}
		
		// Errors exist, have user correct them
		if($form->num_errors > 0)
		{
			return false;
		}
		
		$time = time();
		$database->query("INSERT INTO ".TBL_PROJECT_NEWS." (projectID,title,content,timestamp,author) VALUES ('$projectID','$title','$content',$time,'".$this->username."')");
		return true;
	}
	/**
	* editProjectNews() - Edits given project by user.
	*/
	function editProjectNews($id, $title, $content)
	{
		global $database, $form;
		
		//Title error checking
		$field = "title";
		if(!$title || strlen($title = trim($title)) == 0)
		{
			$form->setError($field, "* Title not entered");
		}
		else
		{
			if(strlen($title) > 50)
			{
				$form->setError($field, "* Title cannot be longer than 50 characters");
			}
			$title = htmlspecialchars($title);
		}
		
		//Content error checking
		$field = "content";
		if(!$content || strlen($content = trim($content)) == 0)
		{
			$form->setError($field, "* Content not entered");
		}
		else
		{
			$content = strip_tags($content,'<a>,<b>,<i>,<font>');
			if(strlen($content) > 65535)
			{
				$form->setError($field, "* Content cannot be longer than 65535 characters");
			}
			else if($this->broken_tags($content))
			{
				$form->setError($field, "* Content has broken HTML tags");
			}
			$content = nl2br($content);
		}
		
		// Errors exist, have user correct them
		if($form->num_errors > 0)
		{
			return false;
		}
		
		$database->query("UPDATE ".TBL_PROJECT_NEWS." SET title='$title',content='$content' WHERE id='$id'");
		return true;
	}
	/**
	* deleteProjectNews() - Checks to see whether the user has the capability
	* to delete the news. Then if able, it deletes it from the database.
	*/
	function deleteProjectNews($projectID, $newsID, $user)
	{
		global $database;
		
		$result = $database->query("SELECT creator FROM ".TBL_PROJECTS." WHERE creator='$user'");
		if(!$result || mysql_num_rows($result)<=0)
		{
			$retval = $database->query("SELECT username FROM".TBL_PROJECT_MEMBERS." WHERE username='$user' AND userlevel>=8");
			if(!$retval || mysql_num_rows($retval)<=0)
			{
				return false;
			}
		}
		
		$database->query("DELETE FROM ".TBL_PROJECT_NEWS." WHERE projectID='$projectID' AND id='$newsID'");
		return true;
	}
	
	/**
	* addFeedback() - Validates fields then stores feedback into the database
	*/
	function addFeedback($username, $name, $email, $subject, $feedback, $securityCode)
	{
		global $database, $form;
		
		if(strcmp($username,GUEST_NAME)==0)
		{
			// Username error checking
			$field = "name";  //Use field name for username
			if(!$name || strlen($name = trim($name)) == 0)
			{
				$form->setError($field, "* Name not entered");
			}
			else
			{
				/* Spruce up username, check length */
				$name = stripslashes($name);
				if(strlen($name) < 3)
				{
					$form->setError($field, "* Name below 3 characters");
				}
				else if(strlen($name) > 30)
				{
					$form->setError($field, "* Name above 30 characters");
				}
				$name = htmlspecialchars($name);
			}
			
			// e-mail error checking
			$field = "email";  //Use field name for email
			if($email && strlen($email = trim($email)) > 0)
			{
				/* Check if valid email address */
				$regex = "^[_+a-z0-9-]+(\.[_+a-z0-9-]+)*"
						."@[a-z0-9-]+(\.[a-z0-9-]{1,})*"
						."\.([a-z]{2,}){1}$";
				if(!eregi($regex,$email))
				{
					$form->setError($field, "* Email invalid");
				}
				$email = stripslashes($email);
			}
			else
			{
				$form->setError($field, "* Email not entered");
			}
			
			//captcha error checking
			$field = "security_code";
			if($_SESSION['security_code'] == $securityCode && !empty($_SESSION['security_code']))
			{
				unset($_SESSION['security_code']);
			}
			else
			{
				$form->setError($field, "* Captcha invalid");
			}
		}
		
		//subject error checking
		$field = "subject";
		if(!$subject || strlen($subject = trim($subject)) == 0)
		{
			$form->setError($field, "* Subject not entered");
		}
		else
		{
			if(strlen($subject) < 3)
			{
				$form->setError($field, "* Subject must be above 3 characters");
			}
			else if(strlen($subject) > 50)
			{
				$form->setError($field, "* Subject must be below 50 characters");
			}
			$subject = htmlspecialchars($subject);
		}
	
		//feedback error checking
		$field = "feedback";
		if(!$feedback || strlen($feedback = trim($feedback)) == 0)
		{
			$form->setError($field, "* Feedback not entered");
		}
		else
		{
			if(strlen($feedback) < 3)
			{
				$form->setError($field, "* Feedback must be above 3 characters");
			}
			else if(strlen($feedback) > 65535)
			{
				$form->setError($field, "* Feedback must be below 65535 characters");
			}
			$feedback = htmlspecialchars($feedback);
		}
		
		// Errors exist, have user correct them
		if($form->num_errors > 0)
		{
			return 1;  //Errors with form
		}
		
		if(strcmp($username,GUEST_NAME)==0)
		{
			$addName = $name;
		}
		else
		{
			$addName = $username;
		}
		
		if($database->addFeedback($this->generateRandID(),$addName,$email,$subject,$feedback))
		{
			return 0;// Success!
		}
		else
		{
			return 2;// Failed
		}
	}

	function resetCountryCounts()
	{
		global $database;
		if($this->userlevel==9)
		{
			$database->query("UPDATE ".TBL_COUNTRIES." SET count='0'");
		}
	}
	function addCountryCount($code)
	{
		global $database;
		$result = $database->query("SELECT count FROM ".TBL_COUNTRIES." WHERE code='$code'");
		$array = mysql_fetch_array($result);

		if($array!=NULL)
		{
			$database->query("UPDATE ".TBL_COUNTRIES." SET count='".($array['count']+1)."' WHERE code='$code'");
		}
	}
	function minusCountryCount($user)
	{
		global $database;
		$result = $database->query("SELECT country FROM ".TBL_USERS." WHERE username='$user'");
		$userArray = mysql_fetch_array($result);

		$result = $database->query("SELECT count FROM ".TBL_COUNTRIES." WHERE code='".$userArray['country']."'");
		$array = mysql_fetch_array($result);

		if($array!=NULL)
		{
			$database->query("UPDATE ".TBL_COUNTRIES." SET count='".($array['count']-1)."' WHERE code='".$userArray['country']."'");
		}
	}

	/**
	* isAdmin - Returns true if currently logged in user is
	* an administrator, false otherwise.
	*/
	function isAdmin()
	{
		return ($this->userlevel == ADMIN_LEVEL || $this->username  == ADMIN_NAME);
	}
	
	/**
	* broken_tags() - checks to see whether or not the given
	* string has tags that were not closed. False if tags were
	* all closed correctly.
	*/
	function broken_tags($str)
	{
		preg_match_all("/(<\w+)(?:.){0,}?>/", $str, $v1);
		preg_match_all("/<\/\w+>/", $str, $v2);
		$open = array_map('strtolower', $v1[1]);
		$closed = array_map('strtolower', $v2[0]);
		foreach ($open as $tag)
		{
			$end_tag = preg_replace("/<(.*)/", "</$1>", $tag);
			if (!in_array($end_tag, $closed)) return true;
			unset($closed[array_search($end_tag, $closed)]);
		}
		return false;
	}

	/**
	* generateRandID - Generates a string made up of randomized
	* letters (lower and upper case) and digits and returns
	* the md5 hash of it to be used as a userid.
	*/
	function generateRandID()
	{
		return md5($this->generateRandStr(16));
	}

	/**
	* generateRandStr - Generates a string made up of randomized
	* letters (lower and upper case) and digits, the length
	* is a specified parameter.
	*/
	function generateRandStr($length)
	{
		$randstr = "";
		for($i=0; $i<$length; $i++)
		{
			$randnum = mt_rand(0,61);
			if($randnum < 10)
			{
				$randstr .= chr($randnum+48);
			}
			else if($randnum < 36)
			{
				$randstr .= chr($randnum+55);
			}
			else
			{
				$randstr .= chr($randnum+61);
			}
		}
		return $randstr;
	}
};
$session = new Session;

$form = new Form;
?>